<template>
  <div class="container">
    <!-- 头部查询 -->
    <div class="search">
      <el-form :inline="true" :model="userQuery" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input v-model="userQuery.name" />
        </el-form-item>
        <el-form-item label="工号">
          <el-input v-model="userQuery.code" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="userQuery.tel" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="userQuery.roleId"
            placeholder="请选择"
          >
            <el-option :value="null">空</el-option>
            <el-option
              v-for="item in optionsRole"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="userSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-container>
      <!-- tree控件 -->
      <el-aside :width="isTreeShow ? '190px' : '0px'">
        <el-menu :collapse="isTreeShow" style="margin-top:8vh;width: 190px;">
          <el-card shadow="always">
            <div slot="header" class="clearfix;">
              <i class="el-icon-menu" @click="treeShow">子系统管理</i>
            </div>
            <el-tree
              :data="treeData"
              accordion
              :highlight-current="true"
              @node-click="handleNodeClick"
            />
          </el-card>
        </el-menu>
      </el-aside>
      <el-main>
        <!-- 操作按钮 -->
        <div class="btn">
          <i class="i-sty el-icon-arrow-right" @click="treeShow" />
          <el-button type="primary" icon="el-icon-plus" @click="userAdd">增加</el-button>
          <el-button type="primary" icon="el-icon-copy-document" @click="userCopy">复制</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="userDelete">删除</el-button>
          <el-dropdown split-button type="primary" style="margin: 0 10px" @command="onStatus">
            启停控制
            <el-dropdown-menu split-button>
              <el-dropdown-item command="start">启用</el-dropdown-item>
              <el-dropdown-item command="stop">停用</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button type="primary" icon="el-icon-plus" @click="roleAssign">分配角色</el-button>
        </div>
        <Table
          :user-data="userData"
          :user-page="userPage"
          :selection="selection"
          :row-copy="rowCopy"
          :row-edit="rowEdit"
          :row-delete="rowDelete"
        />
        <!-- 分页条 -->
        <div class="paginate">
          <el-pagination
            :v-model="userPage"
            :current-page.sync="userPage.pageNum"
            :page-size="userPage.pageSize"
            :page-sizes="userPage.pageSizes"
            layout="total,sizes,prev, pager, next, jumper"
            :total="userPage.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
    <!-- 增加弹窗 -->
    <UserDialog
      ref="UserDialog"
      :user-title="userTitle"
      :user-show="userShow"
      :user-dialog-data="userDialogData"
      :options-department="optionsDepartment"
      :options-position="optionsPosition"
      :options-role="optionsRole"
      :user-close="userClose"
      :user-click="userClick"
    />
    <!-- 分配角色弹窗 -->
    <RoleDialog
      ref="RoleDialog"
      :selections="selections"
      :role-title="roleTitle"
      :role-show="roleShow"
      :role-close="roleClose"
      :role-click="roleClick"
    />
  </div>
</template>

<script>
import { commonQuery, queryAllRole, queryAllDepartment, queryAllPosition, add, queryUserById, modify, batchRemove, batchUpdate } from '../../../api/right/user'
import Table from './table.vue'
import UserDialog from './user-dialog.vue'
import RoleDialog from './role-dialog.vue'
export default {
  name: 'User',
  components: { Table, UserDialog, RoleDialog },
  data() {
    return {
      isTreeShow: false, // tree控件显示与否
      treeData: [], // tree数据
      userData: [], // 用户数据
      userPage: { // 用户表页码
        total: null,
        pageNum: 1, // 页号
        pageSize: 5, // 页大小
        pageSizes: [5, 10, 15, 30, 50, 100, 200],
        pages: null
      },
      selections: [], // 已选择参数
      userQuery: { // 查询传参
        name: '',
        code: '',
        tel: '',
        roleId: '',
        departmentId: '',
        positionId: ''
      },
      optionsRole: [], // 角色数据
      optionsDepartment: [], // 部门数据
      optionsPosition: [], // 职位数据

      commonRolePage: { // 下拉框角色数据
        total: 10,
        pageCount: 1,
        pageSize: 10
      },
      userDialogData: {}, // 初始用户弹窗数据
      userTitle: '', // 增加弹窗标题
      userShow: false, // 增加弹窗显示
      roleList: [], // 角色id
      roleTitle: '角色列表', // 分配角色弹窗标题
      roleShow: false // 分配角色弹窗显示
    }
  },
  created() {
    this.onShow(this.userPage.pageNum)
    this.getRole()
    this.getDepartment()
    this.getPosition()
  },
  methods: {
    // 获取用户数据
    onShow(pageNum) {
      this.userQuery.total = this.userPage.total
      this.userQuery.pageNum = pageNum
      this.userQuery.pageSize = this.userPage.pageSize
      commonQuery(this.userQuery)
        .then((response) => {
          const { total, pages } = response // 如果异常则被axios 的拦截器拦截并且显示错误码和消息
          this.userPage.total = parseInt(total)
          this.userPage.pages = parseInt(pages)
          this.userData = response.data
          console.log(this.userData)
        })
        .catch(() => {
          console.log('网络错误')
        })
    },
    // 获取角色信息
    getRole() {
      queryAllRole()
        .then((response) => {
          const { pageNum, pageSize } = response
          this.commonRolePage.total = response.data.length
          this.commonRolePage.pageNum = pageNum
          this.commonRolePage.pageSize = pageSize
          this.optionsRole = response.data // 角色数据
          this.treeData[2] = { label: '角色', children: [] }
          this.optionsRole.map(item => {
            this.treeData[2].children.push({
              label: item.name,
              id: item.id,
              type: 2
            })
          })
        })
        .catch(() => {
          this.$message.error('网络错误')
        })
    },
    // 获取部门信息
    getDepartment() {
      queryAllDepartment()
        .then((response) => {
          this.optionsDepartment = response.data // 部门数据
          this.treeData[0] = { label: '部门', children: [] }
          this.optionsDepartment.map(item => {
            this.treeData[0].children.push({
              label: item.name,
              id: item.id,
              type: 0
            })
          })
        })
        .catch(() => {
          this.$message.error('网络异常')
        })
    },
    // 获取职位信息
    getPosition() {
      queryAllPosition()
        .then((response) => {
          this.optionsPosition = response.data // 职位数据
          this.treeData[1] = { label: '职位', children: [] }
          this.optionsPosition.map(item => {
            this.treeData[1].children.push({
              label: item.name,
              id: item.id,
              type: 1
            })
          })
        })
        .catch(() => {
          this.$message.error('网络异常')
        })
    },
    // tree点击事件
    handleNodeClick(data) {
      console.log(data.type)
      if (data.id !== null) {
        this.userQuery = {
          name: '',
          code: '',
          tel: '',
          roleId: '',
          departmentId: '',
          positionId: ''
        }
      }
      // 添加搜索参数
      if (data.type === 0) {
        this.userQuery.departmentId = data.id
        console.log(this.userQuery)
      } else if (data.type === 1) {
        this.userQuery.positionId = data.id
        console.log(this.userQuery)
      } else if (data.type === 2) {
        this.userQuery.roleId = data.id
        console.log(this.userQuery)
      }
      console.log(this.userQuery)
      this.onShow(1)
    },
    // 接收Table已选择row
    selection(multipleSelection) {
      this.selections = multipleSelection
    },
    // 显示树控件
    treeShow() {
      this.isTreeShow = !this.isTreeShow
    },
    // 顶部查询
    userSearch() {
      commonQuery(this.userQuery)
        .then((response) => {
          const { total, pages } = response // 如果异常则被axios 的拦截器拦截并且显示错误码和消息
          this.userPage.total = parseInt(total)
          this.userPage.pages = parseInt(pages)
          this.userData = response.data
          console.log(this.userData)
        })
        .catch(() => {
          console.log('网络错误')
        })
    },
    // 更改页的尺寸
    handleSizeChange(val) {
      this.userPage.pageSize = val
      this.onShow(this.userPage.pageNum)
    },
    // 更改页码
    handleCurrentChange(val) {
      this.onShow(val)
    },
    // 增加按钮
    userAdd() {
      this.userTitle = '增加用户'
      this.userShow = true
      setTimeout(() => {
        this.$refs.UserDialog.onShow()
      }, 1)
    },
    // 弹窗关闭事件
    userClose() {
      this.userShow = false
      this.userDialogData = {}
    },
    // 复制事件
    userCopy() {
      if (this.selections == null || this.selections.length === 0) {
        this.$message.error('请选择一条进行拷贝')
        return
      }
      if (this.selections != null && this.selections.length > 1) {
        this.$message.error('只能选择一条进行拷贝')
        return
      } else {
        const selectedUser = this.selections[0]
        queryUserById(selectedUser.id)
          .then((response) => {
          // 加载下拉框数据 设置下拉框的选项
            this.userDialogData = response
            this.userDialogData.roleList = this.userDialogData.roleList.map((item) => item.id)
            this.userTitle = '复制用户'
            this.userDialogData.password = ''
            this.userShow = true
            setTimeout(() => {
              this.$refs.UserDialog.onShow()
            }, 1)
          // 如果修改对话框将更新数据到数据库
          })
          .catch(() => {
            this.$message.error('网络异常')
          })
      }
    },
    // 弹窗确认事件
    userClick(userAdd) {
      if (this.userTitle === '增加用户' || this.userTitle === '复制用户') {
        console.log(this.userTitle)
        userAdd.modifier = this.$store.getters.name
        this.roleList = []
        if (userAdd.roleList) {
          for (let i = 0; i < userAdd.roleList.length; i++) {
            this.roleList[i] = { id: userAdd.roleList[i] }
          }
          userAdd.roleList = this.roleList
        } else {
          userAdd.roleList = []
        }
        const userDTO = userAdd
        userDTO.birthday = this.formatTime(userDTO.birthday)
        console.log(userAdd.roleList)
        add(userDTO)
          .then((response) => {
            // 显示保存成功并且返回
            console.log(response)
            if (response) {
              this.$message.success('操作成功')
            } else {
              this.$message.error('存在该用户工号,不可重复增加')
            }
            this.userShow = false
            this.userDialogData = {}
            this.onShow(1)
          })
          .catch(() => {
            this.userDialogData = {}
            this.$message.error('网络异常')
          })
      } else if (this.userTitle === '编辑用户') {
        userAdd.modifier = this.$store.getters.name
        this.roleList = []
        userAdd.roleList.map(item => {
          this.roleList.push({ id: item })
        })
        userAdd.roleList = this.roleList
        const userDto = userAdd
        userDto.birthday = this.formatTime(userDto.birthday)
        modify(userDto)
          .then((response) => {
            // 显示保存成功并且返回
            this.$message.success('操作成功')
            this.userShow = false
            this.userDialogData = {}
            this.onShow(1)
          })
          .catch(() => {
            this.$message.error('网络异常')
          })
      }
    },
    // 批量删除
    userDelete() {
      const userVOS = this.selections
      if (userVOS == null || userVOS.length === 0) {
        this.$message.error('至少选择一条进行操作')
        return
      }
      this.$confirm('确定删除记录吗').then((response) => {
        const deleteUserVOS = new Array(userVOS.length)
        for (let i = 0; i < userVOS.length; i++) {
          deleteUserVOS[i] = {
            id: userVOS[i].id,
            version: userVOS[i].version
          }
        }
        batchRemove(deleteUserVOS)
          .then((response) => {
            if (response) {
              this.$message.success('删除数据成功')
              this.onShow(1)
            }
          })
          .catch(() => {
            this.$message.error('网络错误')
          })
      })
    },
    // 启用停控
    onStatus(command) {
      switch (command) {
        case 'start': {
          this.onStatusClick(1)
          break
        }
        case 'stop': {
          this.onStatusClick(0)
          break
        }
      }
    },
    onStatusClick(index) {
      const userVOS = this.selections
      if (userVOS == null || userVOS.length === 0) {
        this.$message.error('至少选择一条进行操作')
        return
      }
      const userDOTS = new Array(userVOS.length)
      for (let i = 0; i < userVOS.length; i++) {
        userDOTS[i] = {
          id: userVOS[i].id,
          status: index,
          version: userVOS[i].version
        }
      }
      batchUpdate(userDOTS)
        .then((response) => {
          if (response) {
            this.$message.success('操作成功')
            this.onShow(1)
          } else {
            this.$message.error('没有找到对应记录更新失败')
          }
        })
        .catch(() => {
          this.$message.error('网络错误')
        })
    },
    // 角色分配按钮
    roleAssign() {
      const userVOS = this.selections
      if (userVOS == null || userVOS.length === 0) {
        this.$message.error('至少选择一条进行操作')
        return
      }
      this.roleShow = true
      this.$refs.RoleDialog.onShow()
    },
    // 角色弹窗关闭事件
    roleClose() {
      this.roleShow = false
    },
    // 角色弹窗确认事件
    roleClick() {
      this.roleShow = false
      this.onShow(1)
    },
    rowCopy(row) {
      this.selections = []
      this.selections.push(row)
      this.userCopy()
      this.onShow(1)
    },
    rowEdit(row) {
      const selectedUser = row
      queryUserById(selectedUser.id)
        .then((response) => {
          // 加载下拉框数据 设置下拉框的选项
          this.userDialogData = response
          this.userDialogData.roleList = this.userDialogData.roleList.map((item) => item.id)
          this.userTitle = '编辑用户'
          this.userDialogData.password = ''
          this.userShow = true
          setTimeout(() => {
            this.$refs.UserDialog.onShow()
          }, 1)
          // 如果修改对话框将更新数据到数据库
        })
        .catch(() => {
          this.$message.error('网络异常')
        })
    },
    rowDelete(row) {
      this.selections = []
      this.selections.push(row)
      this.userDelete()
      this.onShow(1)
    },
    // 格式化时间
    formatTime(time) {
      if (!time) {
        return
      }
      time = new Date(time)
      time =
        time.getFullYear() +
        '-' +
        (time.getMonth() + 1 < 10
          ? '0' + (time.getMonth() + 1)
          : time.getMonth() + 1) +
        '-' +
        (time.getDate() < 10 ? '0' + time.getDate() : time.getDate()) +
        ' ' +
        (time.getHours() + 1 < 10 ? '0' + time.getHours() : time.getHours()) +
        ':' +
        (time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()) +
        ':' +
        (time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds())
      return time
    }
  }
}
</script>

<style>
    .container{
      padding: 4vh;
    }
    /* 查询部分 */
    .search{
      width: 100%;
      display: flex;
      align-items: center;
    }
    .table{
      display: flex;
    }
    /* 查询输入框 */
    .input{
      width: 15vw;
      height: 5vh;
      margin-inline: 1vw;
    }
    /* 表格上方操作按钮 */
    .btn{
      margin-block: 4vh;
      height: 5vh;
    }
    /* .userTable{
      height: auto;
    } */
    /* .elBtn{
      margin-inline: 1vw;
    } */
</style>
